import plotly as py
import plotly.figure_factory as ff
pyplt = py.offline.plot

import pandas as pd
from pandas.tseries.offsets import CustomBusinessDay

import random

import data

td = data.data

# Convert Data
def Convert_Data(td):
    tdd = []
    for i in range(1, len(td)):
        xx = {}
        for j in range(0, len(td[i])):
            xx[td[0][j]] = td[i][j]
        tdd.append(xx)
    return tdd

def MakeColor(colors):
    while True:
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)

        if max(r,g,b)-min(r,g,b) <= 10:
            continue

        if len(colors)>0:
            for u in colors:
                if max(g, colors[u]['g'])-min(g, colors[u]['g']) > 10 or max(b, colors[u]['b'])-min(b, colors[u]['b']) > 10 or max(r, colors[u]['r'])-min(r, colors[u]['r']) > 10: 
                    return {'r': r, 'g': g, 'b': b}
        else:
            return {'r': r, 'g': g, 'b': b}

def MakeUserColors(td):
    user_colors = {}
    for data in td:
        if data['Resource'] not in user_colors:
            user_colors[data['Resource']] = MakeColor(user_colors)
            #pass

    for u in user_colors:
        user_colors[u] = F'''rgb({user_colors[u]['r']}, {user_colors[u]['g']}, {user_colors[u]['b']})'''
    #print(user_colors)
    return user_colors


def GenGantt(df):
    colors = MakeUserColors(df)

    fig = ff.create_gantt(df, colors=colors, index_col='Resource', showgrid_y=True,  showgrid_x=True, group_tasks=False, show_colorbar=True)
    pyplt(fig, filename='1.html')
#fig.show()

#start_day = '2021-09-01'
#end_day = '2021-12-31'
def count_businessday(start_day,end_day):
    b = CustomBusinessDay(holidays=data.holidays)
    bus_day = pd.date_range(start=start_day, end=end_day, freq=b)
    length = len(bus_day)
 
    #extra_work_day = ['2021-09-18','2021-09-26','2021-10-09']
    extra_len = 0
    for i in data.extra_work_day:
        if i>=start_day and i<=end_day:
            extra_len = extra_len+1
 
    return length+extra_len


def WordDayAnalysis(df):
    work_days = {}
    for d in df:
        user = d['Resource']
        if user not in work_days:
            work_days[user] = 0
        work_days[user] += count_businessday(d['Start'], d['Finish'])

    return count_businessday(data.start_day, data.end_day), work_days
    #print("总工作日:", )
    #print(work_days)

def Analysis(td):
    df = Convert_Data(td)
    GenGantt(df)
    alldays, wrokdays = WordDayAnalysis(df)
    print("总工作日:", alldays)
    print(wrokdays)

Analysis(td)


